#include <head.h>
#include <sys/stat.h>
#include <errno.h>

void *pthread_read(void *read_fd) {
    int fd = *((int *)read_fd);
    char buf[1024];
    memset(buf, 0, sizeof(buf));
    int byte = 0;
    while (1) {
        memset(buf, 0, sizeof(buf));
        byte = read(fd, buf, sizeof(buf) - 1);
        if (byte <= 0) {
            continue;
        }
        buf[byte] = '\0';

        if (!strcmp(buf, "quit")) {
            printf("退出程序\n");
            return NULL;
        }

        printf("接收: %s strlen = %ld byte = %d\n", buf, strlen(buf), byte);
    }
}

void *pthread_write(void *write_fd) {
    int fd = *((int *)write_fd);
    char buf[1024];
    while (1) {
        printf("请输入要发送的数据: ");
        if (fgets(buf, sizeof(buf), stdin) == NULL) {
            break;
        }
        // 去掉换行符
        size_t len = strlen(buf);
        if (len > 0 && buf[len - 1] == '\n') {
            buf[len - 1] = '\0';
        }

        write(fd, buf, strlen(buf));
        if (!strcmp(buf, "quit")) {
            break;
        }
    }
    return NULL;
}

int main(int argc, char const *argv[]) {
    // 创建有名管道文件
    if (mkfifo("fifo_1", 0666) == -1 && errno != EEXIST) {
        perror("mkfifo fifo_1");
        return -1;
    }
    if (mkfifo("fifo_2", 0666) == -1 && errno != EEXIST) {
        perror("mkfifo fifo_2");
        unlink("fifo_1"); // 删除已创建的 fifo_1
        return -1;
    }

    int fifo_1_fd = open("fifo_1", O_WRONLY);
    if (fifo_1_fd == -1) {
        perror("open fifo_1");
        unlink("fifo_1");
        unlink("fifo_2");
        return -1;
    }
    int fifo_2_fd = open("fifo_2", O_RDONLY);
    if (fifo_2_fd == -1) {
        perror("open fifo_2");
        close(fifo_1_fd);
        unlink("fifo_1");
        unlink("fifo_2");
        return -1;
    }

    pthread_t tid_r, tid_w;

    pthread_create(&tid_r, NULL, pthread_read, (void *)&fifo_2_fd);
    pthread_create(&tid_w, NULL, pthread_write, (void *)&fifo_1_fd);

    pthread_detach(tid_w);

    pthread_join(tid_r, NULL);
    pthread_cancel(tid_w);

    close(fifo_1_fd);
    close(fifo_2_fd);

    // 删除有名管道文件
    unlink("fifo_1");
    unlink("fifo_2");

    return 0;
}